/**
 * Filename: SplashActivity.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/2/23 16:27
 */
package com.github.postsanf.yinian.activity;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;

import com.github.postsanf.yinian.ElseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.huanxin.DemoHelper;
import com.github.postsanf.yinian.service.StatisticsService;
import com.github.postsanf.yinian.utils.DoSecretUtils;
import com.github.postsanf.yinian.utils.SpUtils;
import com.github.postsanf.yinian.utils.StringUtils;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

/**
 * 启动页
 */
public class SplashActivity extends ElseActivity {
    private static final int WHAT_INTENT2MAIN = 2;
    private static final int WHAT_INTENT2LOGINCHOOSE = 4;
    private static final int WHAT_ANIMATION1 = 5;
    private static final int WHAT_ANIMATION2 = 6;
    private static final int WHAT_ANIMATION3 = 7;
    private static final int WHAT_ANIMATION4 = 8;
    private static final int WHAT_ANIMATION5 = 9;
    private static final int WHAT_LOGIN = 10;
    private SharedPreferences sp_login;
    private IWXAPI wxApi;
    private ImageView iv_splash_start1;
    private ImageView iv_splash_start2;
    private ImageView iv_splash_start3;
    private ImageView iv_splash_start4;
    private ImageView iv_splash_yinian;
    private ImageView iv_splash_xiaomi;

    private String uuid;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case WHAT_INTENT2LOGINCHOOSE:
//                    final boolean splashGuide = SpUtils.getBoolean(SplashActivity.this, "splashGuide");
//                    if (splashGuide) {
                    intent2Activity(LoginActivity.class);
                    intent2Activity(LoginWeChatActivity.class);
                    finish();
//                    } else {
//                        startActivity(new Intent(SplashActivity.this, SplashGuideVideoActivity.class));
//                        finish();
//                    }
                    break;
                case WHAT_INTENT2MAIN:
//                    startActivity(new Intent(SplashActivity.this, SplashGuideVideoActivity.class));
                    intent2Activity(MainActivity.class);
                    boolean bb = getSharedPreferences(ACTIONs.mypassword, 0).getBoolean(ACTIONs.numcodepasswordbb, false);
                    if (bb) {
                        intent2Activity(YNCodeLockActivity.class);
                    }
                    finish();
                    break;
                case WHAT_ANIMATION1:
                    iv_splash_start1.setVisibility(View.VISIBLE);
                    ObjectAnimator start1 = ObjectAnimator.ofFloat(iv_splash_start1, "alpha", 0.0f, 1.0f);
                    start1.setDuration(500);
                    start1.setRepeatCount(0);
                    start1.start();
                    break;
                case WHAT_ANIMATION2:
                    iv_splash_start2.setVisibility(View.VISIBLE);
                    ObjectAnimator start2 = ObjectAnimator.ofFloat(iv_splash_start2, "alpha", 0.0f, 1.0f);
                    start2.setDuration(500);
                    start2.setRepeatCount(0);
                    start2.start();
                    break;
                case WHAT_ANIMATION3:
                    iv_splash_start3.setVisibility(View.VISIBLE);
                    ObjectAnimator start3 = ObjectAnimator.ofFloat(iv_splash_start3, "alpha", 0.0f, 1.0f);
                    start3.setDuration(500);
                    start3.setRepeatCount(0);
                    start3.start();
                    break;
                case WHAT_ANIMATION4:
                    iv_splash_start4.setVisibility(View.VISIBLE);
                    ObjectAnimator start4 = ObjectAnimator.ofFloat(iv_splash_start4, "alpha", 0.0f, 1.0f);
                    start4.setDuration(500);
                    start4.setRepeatCount(0);
                    start4.start();
                    break;
                case WHAT_ANIMATION5:
                    iv_splash_yinian.setVisibility(View.VISIBLE);
                    ObjectAnimator start5 = ObjectAnimator.ofFloat(iv_splash_yinian, "alpha", 0.0f, 1.0f);
                    start5.setDuration(500);
                    start5.setRepeatCount(0);
                    start5.start();
//                    try{
//                        ApplicationInfo info=SplashActivity.this.getPackageManager()
//                                .getApplicationInfo(getPackageName(),
//                                        PackageManager.GET_META_DATA);
//                        String infomsg =info.metaData.getString("UMENG_CHANNEL");
//                        if (infomsg.contains("xiaomi")){
//                            iv_splash_xiaomi.setVisibility(View.VISIBLE);
//                            ObjectAnimator start55 = ObjectAnimator.ofFloat(iv_splash_xiaomi, "alpha", 0.0f, 1.0f);
//                            start55.setDuration(500);
//                            start55.setRepeatCount(0);
//                            start55.start();
//                        }else{
//                            iv_splash_xiaomi.setVisibility(View.GONE);
//                        }
//                    }catch (Exception e){
//                        e.printStackTrace();
//                    }
                    break;
                case WHAT_LOGIN:
                    // 新用户
                    if (StringUtils.isEmptyString(uuid) || !DemoHelper.getInstance().isLoggedIn()) {
                        handler.sendEmptyMessage(WHAT_INTENT2LOGINCHOOSE);
                    } else {
                        application.setCurID(Integer.parseInt(uuid));
                        handler.sendEmptyMessage(WHAT_INTENT2MAIN);
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        AnalyticsConfig.enableEncrypt(true);
//        MobclickAgent.setDebugMode(true);
        MobclickAgent.openActivityDurationTrack(false);
        MobclickAgent.setScenarioType(this, MobclickAgent.EScenarioType.E_UM_NORMAL);
        regToWx();
        setContentView(R.layout.yn_activity_splash);
        sp_login = application.getSp_login();
        uuid = DoSecretUtils.getSecretStr(sp_login.getString(getString(R.string.LID), ""));
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "yinian/YiNian");
        if (!(file.mkdir() || file.isDirectory())) {
            file.mkdirs();
        }
        //埋点
        statistics();
        //动画
        initAnimation();
        handler.sendEmptyMessageDelayed(WHAT_LOGIN, 1700);
        SharedPreferences sp = getSharedPreferences("OURINFO", MODE_PRIVATE);
        SharedPreferences.Editor ed = sp.edit();
        ed.putBoolean("active", false);
        ed.commit();
        //经过Splash界面表示程序退出后从新进入
        SharedPreferences spImport = getSharedPreferences("nullUpkey", Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = spImport.edit();
        edit.putBoolean("exit", true);
        edit.commit();

    }

    private void statistics() {
        Long time = SpUtils.getLong(SplashActivity.this, "time");
        toJson(time);
        //继续上传上次上传失败的数据
        String failJson = SpUtils.getString(SplashActivity.this, "failJson");
        if (failJson.startsWith("{")) {
            Intent intent = new Intent(SplashActivity.this, StatisticsService.class);
            intent.setAction(ACTIONs.failJson);
            intent.putExtra("failJson", failJson);
            startService(intent);
//            SpUtils.put(SplashActivity.this,"failJson",null);
        }
    }

    private void toJson(Long time) {
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        try {
            JSONObject jsonObject9 = new JSONObject();
            JSONObject jsonObject10 = new JSONObject();
            JSONObject jsonObject11 = new JSONObject();
            JSONObject jsonObject12 = new JSONObject();

            jsonObject9.put("totalTime", time);
            jsonObject10.put("data", jsonObject9);
            jsonObject10.put("type", 1);
            jsonArray.put(jsonObject10);

            jsonObject11.put("startCount", 1);
            jsonObject12.put("data", jsonObject11);
            jsonObject12.put("type", 2);
            jsonArray.put(jsonObject12);

            jsonObject.put("userid", application.getCurID());
            jsonObject.put("version", getVersion());
            jsonObject.put("device", "Android");
            jsonObject.put("totalData", jsonArray);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Intent intent = new Intent(SplashActivity.this, StatisticsService.class);
        intent.setAction(ACTIONs.uploadRecode);
        intent.putExtra("json", jsonObject.toString());
        startService(intent);
    }

    public String getVersion() {
        try {
            PackageManager manager = this.getPackageManager();
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private void initAnimation() {
        iv_splash_start1 = ((ImageView) findViewById(R.id.iv_splash_start1));
        iv_splash_start2 = ((ImageView) findViewById(R.id.iv_splash_start2));
        iv_splash_start3 = ((ImageView) findViewById(R.id.iv_splash_start3));
        iv_splash_start4 = ((ImageView) findViewById(R.id.iv_splash_start4));
        iv_splash_yinian = ((ImageView) findViewById(R.id.iv_splash_yinian));
        iv_splash_xiaomi = ((ImageView) findViewById(R.id.iv_splash_xiaomi));
        handler.sendEmptyMessageDelayed(WHAT_ANIMATION1, 0);
        handler.sendEmptyMessageDelayed(WHAT_ANIMATION2, 300);
        handler.sendEmptyMessageDelayed(WHAT_ANIMATION3, 600);
        handler.sendEmptyMessageDelayed(WHAT_ANIMATION4, 900);
        handler.sendEmptyMessageDelayed(WHAT_ANIMATION5, 1200);
    }

    private void regToWx() {
        wxApi = WXAPIFactory.createWXAPI(this, getString(R.string.WX_APP_ID));
        wxApi.registerApp(getString(R.string.WX_APP_ID));
        application.setWxApi(wxApi);
    }

    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
